<?php

/**
 * @user magein
 * @date 2023/12/5 18:59
 */

namespace magein\think\utils\api;

use magein\utils\Result;
use magein\think\utils\constants\Code;
use think\facade\Request;
use think\Response;

/**
 * 接口中日常对数据库进行操作，这里是代理不用重复书写路由文件等
 */
class ApiRoute
{
    /**
     * @return Response
     */
    public function dispatch(): Response
    {
        $name = Request::route('_name_');
        $action = Request::route('_action_', '');

        if (empty($name)) {
            return ApiResponse::error('请求参数错误', Code::SERVICE_NAME_ERROR);
        }

        $action = $action ?: 'paginate';

        $service = app()->config->get('api.service.' . $name);

        if (empty($service)) {
            return ApiResponse::error('尚未匹配服务', Code::SERVICE_NO_FOUND);
        }

        if (!class_exists($service)) {
            return ApiResponse::error('尚未匹配服务', Code::SERVICE_NO_FOUND);
        }

        $service = new $service();
        if (!$service instanceof ApiBaseService) {
            return ApiResponse::error('服务类异常', Code::SERVICE_CLASS_ERROR);
        }

        if (!method_exists($service, $action)) {
            return ApiResponse::error('请求行为不支持', Code::SERVICE_ACTION_ERROR);
        }

        $data = $service->$action();

        if ($data instanceof Result) {
            return ApiResponse::result($data);
        }

        return ApiResponse::success($data);
    }

}